<?php
// 處室資料升級
class Default_Model_Upgrade_SchoolRoom extends Default_Model_Upgrade_Core
{
    protected $_table = 'school_room';
    protected $_targetTable = array('school_room');
    function upgrade (){
        if ($this->isUpgrade())
        return 'isUpgrde';
        else {
            $query = "SELECT * FROM school_room";

            $res = $this->_sfs3Pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);

            $log = array();
            $success_count = 0;
            $error_count = 0;
            $rank = 0;
            foreach($res as $row){
                $arr = array();
                //  $role_arr = array();
                // $arr['sn'] = $row['room_id'];
                $arr['name'] = $this->iconv($row['room_name']);
                $arr['phone'] = $this->iconv($row['room_tel']);
                $arr['enable'] = ($row['enable']==1)?'Y':'N';
                $arr['rank'] = ++$rank ;
                //                $role_arr['id'] = $arr['name'];
                //                $role_arr['role_kind'] = 'room';
                $query = "SELECT name FROM school_room WHERE name='{$arr['name']}'";
                $find = $this->_newdbPdo->query($query)->fetchAll();
                if (count($find) ==0){

                    $res = $this->fromArray('school_room', $arr) ;
                    //                    $query  = "INSERT INTO  school_room (".implode(',',array_keys($arr)).") VALUES('".implode("','",array_values($arr))."')";
                    //                    $res = $this->_newdbPdo->exec($query) or die($query);
                    // 加入存取角色
                    if ($res) {
                        // 加入 acl_roles
                        $arr2 = array();
                        $arr2['id'] = $arr['name'];
                        $arr2['role_kind'] = 'room';
                        $this->fromArray('acl_roles',$arr2);
                        $success_count++ ;
                    }
                    else {
                        $query = "SELECT name FROM school_room WHERE name='{$arr['name']}'";
                        $log['error_row'][] = $query;//$row['room_id'];
                        $error_count++;
                    }
                }

            }

            $log['success_count'] = $success_count;
            $log['error_count'] = $error_count;
            $log['memo'] = 'SFS3 處室資料升級';
            $log['upgrade_time']	= date("Y-m-d h:i:s");

            $this->finishUpgrade($log);
        }
    }

}